package com.qd.panda.card;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cdqidi.dto.ApiResult;
import com.cdqidi.dto.ApiResultWrapper;
import com.cdqidi.dto.DelDTO;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.page.BaseQuery;
import com.cdqidi.util.page.PageUtil;
import com.cdqidi.valid.group.DefaultGroup;
import com.cdqidi.valid.group.UpdateGroup;
import com.qd.common.panda.domain.entity.card.CardPlanDTO;
import com.qd.common.panda.domain.entity.card.CardPlanRedeemCodeDTO;
import com.qd.common.panda.domain.entity.card.redeemcode.PlanRedeemCodeDTO;
import com.qd.common.panda.domain.entity.card.redeemcode.PlanRedeemCodeDetailDTO;
import com.qd.common.sys.annotation.OperatorInfo;
import com.qd.common.sys.enums.OperatorType;
import com.qd.common.sys.util.SecurityUtils;
import com.qd.panda.service.card.CardPlanHolderService;
import com.qd.panda.service.card.CardPlanRedeemCodeService;
import com.qd.panda.service.card.CardPlanService;
import com.qd.panda.service.card.collect.CollectCardService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * /优惠券/WEB_发券计划
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Validated
@RestController
@RequestMapping("/sys/cardPlan/")
@Slf4j
public class CardPlanController {
    private final CardPlanHolderService cardPlanHolderService;
    private final CardPlanService cardPlanService;
    private final CardPlanRedeemCodeService cardPlanRedeemCodeService;
    private final CollectCardService collectCardService;

    /**
     * 添加发券计划
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @PreAuthorize("@ps.hasPermission('business:activityList:save')")
    @OperatorInfo(title = "添加", operator = OperatorType.INSERT, isAuditLog = false)
    @PostMapping(value = "/save")
    public CardPlanDTO save(@Validated({DefaultGroup.class}) @RequestBody CardPlanDTO dto) {
        dto.setAddTime(LocalDateTime.now());
        dto.setOperator(SecurityUtils.getLoginUser().getUserId());
        dto.setOrgId(SecurityUtils.getLoginUser().getCurrentOrgId());
        return cardPlanHolderService.save(dto);
    }

    /**
     * 修改发券计划
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @PreAuthorize("@ps.hasPermission('system:userCard:edit')")
    @OperatorInfo(title = "修改", operator = OperatorType.UPDATE, isAuditLog = false)
    @PutMapping(value = "/update")
    public CardPlanDTO update(@Validated({UpdateGroup.class, DefaultGroup.class}) @RequestBody CardPlanDTO dto) {
        dto.setUpdateTime(LocalDateTime.now());
        dto.setOperator(SecurityUtils.getLoginUser().getUserId());
        dto.setOrgId(SecurityUtils.getLoginUser().getCurrentOrgId());
        return cardPlanHolderService.update(dto);
    }

    /**
     * 删除发券计划
     *
     * @param delDTO delDTO中的ids,主键
     * @return 成功 or 失败
     */
    @PreAuthorize("@ps.hasPermission('business:activityList:delete')")
    @OperatorInfo(title = "删除", operator = OperatorType.DELETE, isAuditLog = false)
    @DeleteMapping(value = "/delete")
    public ApiResultWrapper<Object> delete(@Validated @RequestBody DelDTO<String> delDTO) {
        List<String> ids = delDTO.getIds();
        if (ids.size() == 1) {
            cardPlanHolderService.delete(ids.get(0));
        } else {
            cardPlanHolderService.deleteIds(ids);
        }
        return ApiResult.success("删除成功");
    }

    /**
     * 获取发券计划
     *
     * @param id 主键
     * @return 记录
     */
    @GetMapping(value = "/getById")
    public CardPlanDTO getById(@Validated @NotBlank(message = "ID不能为空") String id) {
        return cardPlanService.getByIdDto(id);
    }

    /**
     * 发券计划列表
     *
     * @param dto 查询参数以及页数和每页显示条数
     * @return 列表信息
     */
    @GetMapping(value = "/page")
    public IPage<CardPlanDTO> page(CardPlanDTO dto) {
        return cardPlanService.page(PageUtil.buildPage(dto), dto);
    }

    /**
     * 导出兑换码
     *
     * @param planId 计划ID
     */
    @PreAuthorize("@ps.hasPermission('business:activityList:export')")
    @OperatorInfo(title = "兑换码导出", operator = OperatorType.EXPORT)
    @GetMapping(value = "/exportRedeemCode")
    public void exportRedeemCode(@Validated @NotBlank(message = "计划ID不能为空") String planId) {
        if (collectCardService.existsByPlanId(planId)) {
            throw new ApiException("已经配置了自动领卷，不支持导出兑换码");
        }
        CardPlanRedeemCodeDTO query = new CardPlanRedeemCodeDTO();
        query.setPlanId(planId);
        cardPlanRedeemCodeService.export(query);
    }

    /**
     * 使用数量统计
     *
     * @param planId 计划ID
     * @return 统计
     */
    @GetMapping(value = "/useRedeemCode")
    public PlanRedeemCodeDTO useRedeemCode(@Validated @NotBlank(message = "计划ID不能为空") String planId) {
        return cardPlanHolderService.useRedeemCode(planId);
    }


    /**
     * 在线查看兑换码
     *
     * @param planId 计划ID
     */
    @PreAuthorize("@ps.hasPermission('system:userCard:onlineRedeemCode')")
    @OperatorInfo(title = "在线查看兑换码", operator = OperatorType.OTHER)
    @GetMapping(value = "/onlineRedeemCode")
    public void onlineRedeemCode(@Validated @NotBlank(message = "计划ID不能为空") String planId) throws IOException {
        CardPlanRedeemCodeDTO query = new CardPlanRedeemCodeDTO();
        query.setPlanId(planId);
        cardPlanRedeemCodeService.onlineRedeemCode(query);
    }

    /**
     * 可用发劵计划
     */
    @GetMapping(value = "/availableCardPlan")
    public List<CardPlanDTO> availableCardPlan() {
        return cardPlanService.availableCardPlan();
    }

    /**
     * 兑换-使用明细列表
     *
     * @param planId 计划ID
     */
    @GetMapping(value = "/useRedeemCodeDetailPage")
    public IPage<PlanRedeemCodeDetailDTO> useRedeemCodeDetailPage(@Validated @NotBlank(message = "计划ID不能为空") String planId, @Validated @NotNull(message = "类型不能为空") Integer type, String cardMsgId, BaseQuery baseQuery) {
        return cardPlanHolderService.useRedeemCodeDetailPage(PageUtil.buildPage(Optional.ofNullable(baseQuery).orElse(new BaseQuery())), planId, cardMsgId, type);
    }
}